import os
import subprocess

from conf import conf
def append_zeros(filepath, n):
    # 文件纵向对齐到 16 字节
    with open(filepath, "ab") as f:
        f.write(b'\x00' * 16 * n)



def split_bits(input_path,output_path):
    with open(input_path, 'rb') as f_in:
        # 初始化128个输出文件和对应的缓冲区
        files = []
        buffers = []
        for i in range(128):
            file_name = output_path+"/"+f"{i + 1}.bin"
            # 以二进制写入模式打开文件
            f = open(file_name, 'wb')
            files.append(f)
            buffers.append({'buffer': 0, 'count': 0})

        while True:
            chunk = f_in.read(16)  # 每次读取16字节（128位）
            if not chunk:
                break

            # 处理当前块中的每个字节的每个位
            for byte_idx, byte in enumerate(chunk):
                for bit_pos in range(8):  # 从高位到低位处理每个位
                    # 计算全局位索引（0到127）
                    global_bit = byte_idx * 8 + bit_pos
                    # 获取对应的文件索引
                    file_idx = global_bit
                    # 提取当前位的值（0或1）
                    bit = (byte >> (7 - bit_pos)) & 0x01

                    # 更新对应的缓冲区
                    current = buffers[file_idx]
                    current['buffer'] = (current['buffer'] << 1) | bit
                    current['count'] += 1

                    # 如果缓冲区已满，写入文件并重置
                    if current['count'] == 8:
                        files[file_idx].write(bytes([current['buffer']]))
                        current['buffer'] = 0
                        current['count'] = 0

        # 处理所有剩余未写入的缓冲区
        for i in range(128):
            current = buffers[i]
            if current['count'] > 0:
                # 左移补零，组成一个字节
                remaining = current['buffer'] << (8 - current['count'])
                files[i].write(bytes([remaining]))

        # 关闭所有输出文件
        for f in files:
            f.close()

def work():
    base_dir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/') + "/../../"
    t0  =base_dir + "data/client/t0.bin"
    t1  =base_dir + "data/client/t1.bin"
    out1 = base_dir + "data/client/t0/"
    out2 = base_dir + "data/client/t1/"
    config = conf.read_json()
    tot_nums = (config['bucket_num']+3) % 128 # 128 位总数
    add_nums = 128 - tot_nums # 需要补充的位数
    append_zeros(t0, add_nums) # 补充 0
    append_zeros(t1, add_nums)
    exec_path = base_dir + "bin/split_128.exe"
    # split_bits(t0, out1)
    # split_bits(t1, out2)
    subprocess.run([exec_path, t0, out1])
    subprocess.run([exec_path, t1, out2])
if __name__ == '__main__':
    work()